package com.runyu.cordova.plugin.crypto;

import java.util.ArrayList;
import java.util.List;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;

import com.honeywell.aidc.AidcManager;
import com.runyu.cordova.plugin.JsActionSupport;
import com.runyu.cordova.plugin.barcode.AidcManagerCreatedListener;

import android.content.Context;

public class LicenseManager implements AidcManagerCreatedListener, JsActionSupport {

	private AidcManager manager;

	private CordovaInterface cordova;
	private static final String ACTION_CHECK_LICENSE = "checkLicense";
	private static final String ACTION_SUBJECT_LICENSE = "subjectLicense";

	public LicenseManager(CordovaInterface cordova) {
		this.cordova = cordova;
	}

	public boolean subjectLicense(String key) {
		if (this.manager == null) {
			return false;
		}
		Context applicationContext = this.cordova.getActivity().getApplicationContext();
		return NativeLicense.subjectLicense(this.manager, applicationContext, key);
	}

	public boolean checkLicense() {
		Context applicationContext = this.cordova.getActivity().getApplicationContext();
		return NativeLicense.checkLicense(this.manager, applicationContext);
	}

	@Override
	public void onCreated(AidcManager aidcManager) {
		this.manager = aidcManager;
	}

	@Override
	public List<String> getSupportAction() {
		List<String> list = new ArrayList<>();
		list.add(ACTION_CHECK_LICENSE);
		list.add(ACTION_SUBJECT_LICENSE);
		return list;
	}

	@Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		if (ACTION_SUBJECT_LICENSE.equals(action)) {
			String content = args.get(0).toString();
			boolean success = this.subjectLicense(content);
			if (!success) {
				callbackContext.error("License subject failed");
				return false;
			}
			callbackContext.success();
			return true;
		}

		if (ACTION_CHECK_LICENSE.equals(action)) {
			boolean success = this.checkLicense();
			if (!success) {
				callbackContext.error("License check failed");
				return false;
			}
			callbackContext.success();
			return true;
		}
		return false;
	}
}
